import React, { useEffect, useState, FC } from 'react'
import Taro from '@tarojs/taro'
import { View, Text, Radio, RadioGroup, Label, Button, Picker } from '@tarojs/components'
import { useSelector } from 'react-redux'
import { AtIcon, AtInput, AtTextarea } from 'taro-ui'
import { AddressObj } from '@/constants/commonType'
import Photograph from '@/components/Photograph/index'
import api from '@/services/config/index'
import { timeFilter } from '@/utils/common'
import './index.scss'

type ClassifyList = Array<{
  id: string
  catName: string
  icon?: string
  countNum?: string
}>

interface FormValue {
  action: 1 | 2 | 3 | 4
  catId: string
  title: string
  description: string
  picture: string
  addressId: string
  startAt: string
  deadlineAt: string
  sharePoints: string | undefined
  inventory: string
  deposit: string
  isNeedReturn: string
  districtId: string | number
}
type useSelectorState = {
  address: AddressObj
}
const ReleaseItems: FC = () => {
  const address = useSelector((state: useSelectorState) => state.address)
  const [classifyList, setClassifyList] = useState<ClassifyList>([])
  const [classifyName, setClassifyName] = useState<string>('')
  const [formValue, setformValue] = useState<FormValue>({
    action: 1,
    catId: '', // 分类id
    title: '', // 标题
    description: '', //物品描述
    picture: '', //图片路径
    addressId: '', //地址id
    startAt: '', //开始时间
    deadlineAt: '', //结束时间
    sharePoints: '', //物品积分值
    inventory: '', // 库存
    deposit: '', //押金 需要归还的物品需支付押金
    isNeedReturn: '1', //是否需要归还
    districtId: '' //小区id
  })
  const [fileList, setFileList] = useState<Array<{ uploadUrl: string; url: string }>>([])

  const [radioList] = useState([
    {
      value: '1',
      text: '是',
      checked: true
    },
    {
      value: '0',
      text: '否'
    }
  ])

  // 获取分类列表
  function getShareCat() {
    api['itemSharing/getShareCat']().then((res) => {
      const data = res.data
      setClassifyList(data)
    })
  }

  useEffect(() => {
    getShareCat()
  }, [])

  function handleChange(value, key) {
    console.log(typeof value)

    if (key === 'offline') return
    const data = {}
    data[key] = value
    setformValue({ ...formValue, ...data })
  }

  // 选择分类列表
  function onChangePicker(e) {
    const value = e.detail.value
    setClassifyName(classifyList[value].catName)
    setformValue({ ...formValue, catId: classifyList[value].id })
  }
  // 过滤分类列表
  function rangeClassifyList() {
    const list: string[] = []
    classifyList.map((item) => {
      list.push(item.catName)
    })
    return list
  }
  // 共享日期
  function onDateChange(e, type) {
    if (type === 'startAt') {
      setformValue({ ...formValue, startAt: e.detail.value })
    } else {
      setformValue({ ...formValue, deadlineAt: e.detail.value })
    }
  }
  // 表单验证
  function formValidation(_formValue) {
    const {
      catId,
      title,
      description,
      picture,
      addressId,
      sharePoints,
      startAt,
      deadlineAt,
      inventory,
      deposit,
      isNeedReturn
    } = _formValue
    return [
      {
        judgeKey: catId,
        tips: '请选择分类'
      },
      {
        judgeKey: title,
        tips: '请输入标题'
      },
      {
        judgeKey: () => {
          if (description.length < 10) {
            return true
          } else {
            return false
          }
        },
        tips: '描述物品信息不得少于10个字'
      },
      {
        judgeKey: picture,
        tips: '请上传图片'
      },
      {
        judgeKey: addressId,
        tips: '请选择地址'
      },
      {
        judgeKey: sharePoints - 0 <= 25,
        tips: '所需积分不能大于25'
      },
      {
        judgeKey: startAt,
        tips: '请选择开始时间'
      },
      {
        judgeKey: deadlineAt,
        tips: '请选择结束时间'
      },
      {
        judgeKey: inventory,
        tips: '请输入库存'
      },
      {
        judgeKey: () => {
          if (isNeedReturn === '1' && !deposit) {
            return true
          } else {
            return false
          }
        },
        tips: '请输入所押积分'
      }
    ]
  }
  //发布
  function release() {
    // 将上传的图片地址转换成以逗号拼接的形式
    let picture = ''
    fileList.map((item) => {
      picture += item.uploadUrl + ','
    })
    picture = picture.substr(0, picture.length - 1)
    const _formValue = {
      ...formValue,
      picture,
      addressId: address.addressId,
      districtId: address.district && address.district.districtId
    }
    // 表单校验
    let flag = false
    let tips = ''
    const _formValidation = formValidation(_formValue)
    for (const item of _formValidation) {
      if (typeof item.judgeKey === 'function') {
        if (item.judgeKey()) {
          tips = item.tips
          flag = true
          break
        }
      } else if (!item.judgeKey) {
        flag = true
        tips = item.tips
        break
      }
    }
    // 如果为true，说明表单校验不通过
    if (flag) {
      Taro.showToast({
        title: tips,
        icon: 'none'
      })
      return
    }
    api['itemSharing/addShare'](_formValue).then((_) => {
      Taro.showToast({
        title: '发布物品成功',
        icon: 'none'
      })
      Taro.navigateBack({ delta: 1 })
    })
  }

  return (
    <View className='releaseItems'>
      <View className='container-top'>
        {/* 分类 */}
        <Picker mode='selector' range={rangeClassifyList()} onChange={onChangePicker} value={1}>
          <View className='releaseItems-classify inpput-commom b-bottom'>
            <View className='releaseItems-classify--titie'>
              <View>分类：</View>
              <View className='grey-color'>{classifyName}</View>
            </View>
            <AtIcon value='chevron-right' size='20' color='#bbbbbb'></AtIcon>
          </View>
        </Picker>
        {/* 标题*/}
        <View className='releaseItems-brand inpput-commom b-bottom'>
          <AtInput
            name='title'
            placeholder='请输入标题'
            placeholderClass='classify-placeolder'
            value={formValue.title}
            onChange={(value) => {
              handleChange(value, 'title')
            }}
            border={false}
          ></AtInput>
        </View>
        {/* 物品细节描述 */}
        <View className='releaseItems-details b-bottom'>
          <AtTextarea
            value={formValue.description}
            placeholder='请描述一下物品的细节或故事（最少10字以上）'
            className='releaseItems-details--txt'
            placeholderClass='details-placeolder'
            onChange={(value) => {
              handleChange(value, 'description')
            }}
            maxLength={200}
          />
        </View>
        {/* 上传图片 */}
        <View className='releaseItems-upload b-bottom'>
          <Photograph
            fileList={fileList}
            onHandChange={(file) => {
              setFileList(file)
            }}
          ></Photograph>
        </View>
        {/* 地址 */}
        <View
          className='releaseItems-address'
          onClick={() => {
            Taro.navigateTo({
              url: '/pages/Address/index'
            })
          }}
        >
          <View>
            <AtIcon prefixClass='icon' value='location' size='20' color='##666666'></AtIcon>
            <Text className='releaseItems-address--txt'>{address.addressDetail}</Text>
          </View>
          <View>
            <AtIcon value='chevron-right' size='25' color='#bbbbbb'></AtIcon>
          </View>
        </View>
      </View>
      {/* 容器bottom */}
      <View className='container-bottom'>
        {/* 所需积分 */}
        <View className='releaseItems-integral inpput-commom b-bottom'>
          <Text>所需积分:</Text>
          <AtInput
            placeholder='请输入所需积分'
            type='number'
            name='sharePoints'
            placeholderClass='classify-placeolder'
            value={formValue.sharePoints}
            onChange={(value) => {
              handleChange(value, 'sharePoints')
            }}
            border={false}
          ></AtInput>
        </View>
        {/* 共享日期 */}
        <View className='releaseItems-date inpput-commom b-bottom'>
          <Text className='releaseItems-date__title'>共享日期:</Text>
          <Picker
            start={timeFilter(new Date(), 'YYYY-MM-DD')}
            className='releaseItems-date__start'
            mode='date'
            onChange={(e) => {
              onDateChange(e, 'startAt')
            }}
            value={formValue.startAt}
          >
            <Text>{formValue.startAt || '开始时间'}</Text>
          </Picker>
          <Text className='releaseItems-date__partition'>至</Text>
          <Picker
            start={timeFilter(new Date(), 'YYYY-MM-DD')}
            className='releaseItems-date__end'
            mode='date'
            onChange={(e) => {
              onDateChange(e, 'deadlineAt')
            }}
            value={formValue.deadlineAt}
          >
            <Text>{formValue.deadlineAt || '结束时间'}</Text>
          </Picker>
        </View>
        {/* 库存 */}
        <View className='inpput-commom b-bottom'>
          <Text>库存:</Text>
          <AtInput
            name='inventory'
            placeholder='请输入库存'
            placeholderClass='classify-placeolder'
            value={formValue.inventory}
            onChange={(value) => {
              handleChange(value, 'inventory')
            }}
            border={false}
          ></AtInput>
        </View>
        {/* 押积分 */}
        {formValue.isNeedReturn === '1' ? (
          <View className='inpput-commom b-bottom'>
            <Text>押积分:</Text>
            <AtInput
              name='deposit'
              placeholder='请输入押积分'
              placeholderClass='classify-placeolder'
              value={formValue.deposit}
              onChange={(value) => {
                handleChange(value, 'deposit')
              }}
              border={false}
            ></AtInput>
          </View>
        ) : (
          ''
        )}
        {/* 是否需要归还 */}
        <View className='inpput-commom b-bottom'>
          <Text>是否需要归还:</Text>
          <RadioGroup>
            {radioList.map((item) => {
              return (
                <Label
                  key={item.value}
                  onClick={() => {
                    setformValue({ ...formValue, isNeedReturn: item.value })
                  }}
                >
                  <Radio
                    value={item.value}
                    checked={item.checked}
                    color='#f0593d'
                    className='revert-radios'
                  >
                    {item.text}
                  </Radio>
                </Label>
              )
            })}
          </RadioGroup>
        </View>
        {/* 交易方式 */}
        <View className='inpput-commom b-bottom'>
          <Text>交易方式:</Text>
          <AtInput
            name='offline'
            value='线下交易'
            placeholderClass='classify-placeolder'
            onChange={() => {
              handleChange(null, 'offline')
            }}
            border={false}
            disabled
          ></AtInput>
        </View>
        <Button className='releaseItems-release' onClick={release}>
          确认发布
        </Button>
      </View>
    </View>
  )
}

export default ReleaseItems
